import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {PageSubject} from '../../../util/page-subject';
import {ResponseUtil} from '../../../util/response-util';
import {TableUtil} from '../../../util/table-util';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {OneOperationComponent} from '../../../widgets/one-operation/one-operation.component';
import {SiteCategorysService} from './site-categorys.service';
import {MsgResult} from '../../../models/msg-result';
import {API, MsgConstants} from '../../../constants/constants';
import {ActivatedRoute, Router} from '@angular/router';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {DataDictionaryService} from '../../../services/dataDictionary.service';
import {SiteV2API} from '../site-v2-constants';

@Component({
  selector: 'app-site-categorys',
  templateUrl: './site-categorys.component.html',
  styleUrls: ['./site-categorys.component.css']
})
export class SiteCategorysComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  proxy = {
    'siteCateAdd': () => this.siteCateAdd(),
    'siteCateUpdate': () => this.siteCateUpdate(),
    'siteCateDelete': () => this.siteCateDate()
  };

  siteCateName: string;
  siteCateType: string;

  // 站点
  siteCode = '';

  table: any;

  siteCateId: string;
  siteCateIds: Array<any> = [];

  // 数据字典中获取数据的编码
  dicPolluteType = 'ZDLEWRY';
  dicFuncCate = 'ZDLX';
  dicPolluteArr: Array<any> = [];
  dicFuncCateArr: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private tableUtil: TableUtil,
    private siteCateService: SiteCategorysService,
    private dicService: DataDictionaryService,
    private dialogService: OneDialogService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.getDicPolluteType();
  }
  ngAfterViewInit() {
    // 操作函数代理
    this.operation.proxy = this.proxy;
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('设备接入管理', '');
    this.pageSubject.pushPage('站点类型', '查询', path);
  }

  /**
   * 加载表格
   */
  loadSiteCate() {
    this.table = this.tableUtil.load('one_table_site-cate',  {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        {field: 'siteTypeName', title: '站点类型', align: 'left'},
        {field: 'siteTypeCode', title: '编码', align: 'left'},
        {field: 'monitorCategory', title: '监测类别', align: 'left', formatter: this.formatPolluteType},
        {field: 'functionalCategory', title: '功能性类别',  align: 'left', formatter: this.formatFuncCateType},
        {field: 'isUse', title: '启用', align: 'left', formatter: this.yesOrNoFormat},
        {field: 'remark', title: '说明', align: 'left'}
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_site-cate',
      url: SiteV2API.siteCatePageListV2,
      method: 'post',
      // 传递附加参数
      queryParams: (params) => {
        params.siteTypeName = this.siteCateName;
        params.monitorCategory = this.siteCateType;
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {

        });
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true, // 响应式
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
    });
  }

  /**
   * 格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {string}
   */
  private yesOrNoFormat = (value, row, index) => {
    if (value === '1') {
      return '是';
    }
    if (value === '0') {
      return '否';
    }
  };
  private formatPolluteType = (value) => {
    let display = '';
    this.dicPolluteArr.every((val) => {
      if (val.value === value) {
        display = val.display;
        return false;
      } else {
        return true;
      }
    });
    return display;
  };
  private formatFuncCateType = (value) => {
    let display = '';
    this.dicFuncCateArr.every((val) => {
      if (val.value === value) {
        display = val.display;
        return false;
      } else {
        return true;
      }
    });
    return display;
  };
  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 添加账户
   */
  siteCateAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 批量删除
   */
  siteCateDate() {
    const rows = this.table.bootstrapTable('getSelections');
    this.siteCateIds = this.tableUtil.getCloumns(rows, 'id');
    if (this.siteCateIds.length === 0) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', this.requestDelete);
    }
  }


  /**
   * 实现批量删除操作
   * 1.判断id字符串是否存在
   * 2.调取后端删除操作；
   */
  private requestDelete = () => {
    if (!!this.siteCateIds) {
      this.siteCateService.deleteSiteCate(this.siteCateIds.join(',')).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    } else {
      this.dialogService.modalInfo('请选择一条数据');
    }
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 修改账户信息
   */
  siteCateUpdate() {
    const rows = this.table.bootstrapTable('getSelections');
    if (rows.length !== 1) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.siteCateId = this.tableUtil.getCloumn(rows[0], 'id');
      this.router.navigate(['update', {siteCateId: this.siteCateId}], {relativeTo: this.route});
    }
  }

  /**
   * 获取数据字典中站点类型-大类
   */
  getDicPolluteType () {
    this.dicService.getChildDicByCode(this.dicPolluteType).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicPolluteArr = result.data;
            this.getDicFuncCate();
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  getDicFuncCate = () => {
    this.dicService.getChildDicByCode(this.dicFuncCate).subscribe(
      result => this.responseUtil.success(result, () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicFuncCateArr = result.data;
            this.loadSiteCate();
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
}
